# -*- coding:binary -*-
require 'spec_helper'

RSpec.describe Msf::Exploit::Remote::SMB::Client::RemotePaths do
  subject do
    mod = ::Msf::Module.new
    mod.extend described_class
    mod
  end

  before(:context) do
    prefix = "remote_#{Rex::Text.rand_text_alpha(10)}"
    # create a single random file to be used for RPATH
    @rpath = prefix
    # create file containing several random file names to be used for FILE_RPATHS
    @indices = Array(0..(1 + rand(5))).map(&:to_s)
    @file_rpaths = Tempfile.new(prefix)

    File.open(@file_rpaths, 'wb') do |f|
      @indices.map do |i|
        f.puts(i)
      end
    end
  end

  describe '#validate_rpaths!' do
    context 'when RPATH and FILE_RPATHS are not set correctly' do
      it 'raises if both are set' do
        subject.datastore['RPATH'] = @rpath
        subject.datastore['FILE_RPATHS'] = @file_rpaths
        expect { subject.validate_rpaths! }.to raise_error(Msf::OptionValidateError, /FILE_RPATHS/)
      end

      it 'raises if neither are set' do
        expect { subject.validate_rpaths! }.to raise_error(Msf::OptionValidateError, /FILE_RPATHS/)
      end
    end

  end

  describe '#remote_paths' do
    context 'when RPATH and FILE_RPATHS are set correctly' do
      it 'returns one remote file if rpath is set' do
        subject.datastore['RPATH'] = @rpath
        expect(subject.remote_paths).to eql([@rpath])
      end

      it 'returns all files if FILE_RPATHS is set' do
        subject.datastore['FILE_RPATHS'] = @file_rpaths
        expect(subject.remote_paths).to eql(@indices)
      end
    end
  end

  after(:context) do
    @file_rpaths.unlink
  end
end
